package com.leyou.search.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.SpecParam;
import com.leyou.item.pojo.Spu;
import com.leyou.item.pojo.SpuDetail;
import com.leyou.search.clients.CategoryClient;
import com.leyou.search.clients.GoodsClient;
import com.leyou.search.clients.SpecClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class IndexService {

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private SpecClient specClient;

    @Autowired
    private GoodsRepository goodsRepository;


    public Goods buildGoods(SpuBo spuBo){
        Goods goods = new Goods();

        //相同属性赋值
        BeanUtils.copyProperties(spuBo,goods);

        //四个值无法赋值，所以需要手动加值

        // 所有需要被搜索的信息，包含标题，分类，甚至品牌

        List<String> names = categoryClient.queryNameByIds(Arrays.asList(spuBo.getCid1(), spuBo.getCid2(), spuBo.getCid3()));

        String all = spuBo.getTitle()+" "+ StringUtils.join(names," ");
        goods.setAll(all);

        //goods.setSkus();

        //根据spuId查询当前所有的sku
        List<Sku> skus = this.goodsClient.querySkuBySpuId(spuBo.getId());

        //存sku价格
        List<Long> prices = new ArrayList<>();

        //存储sku
        List<Map<String,Object>> skuList = new ArrayList<>();

        for (Sku sku : skus) {
            prices.add(sku.getPrice());
            Map<String,Object> skuMap = new HashMap<>();
            skuMap.put("id",sku.getId());
            skuMap.put("title",sku.getTitle());
            //把每个sku规定只能有一个图片
            skuMap.put("image", StringUtils.isBlank(sku.getImages()) ? "":sku.getImages().split(",")[0]);
            skuMap.put("price",sku.getPrice());
            skuList.add(skuMap);
        }

        //设置价格集合
        goods.setPrice(prices);

        goods.setSkus(JsonUtils.serialize(skuList));

        //goods.setPrice();

        //goods.setSpecs();


        //获取所有的可搜索的规格参数
        List<SpecParam> searchParams = this.specClient.querySpecParam(null, spuBo.getCid3(), true,null);


        //根据spuId查询spuDetail用来取通用规格参数以及特有规格参数的值

        SpuDetail spuDetail = this.goodsClient.querySpuDetailById(spuBo.getId());

        //获取通用规格属性信息，并转成map 1:华为，2:Mate 20
        Map<Long,Object> genericMap = JsonUtils.nativeRead(spuDetail.getGenericSpec(), new TypeReference<Map<Long, Object>>() {
        });

        //获取特有规格属性信息，转成map
        Map<Long,List<String>> specialMap = JsonUtils.nativeRead(spuDetail.getSpecialSpec(), new TypeReference<Map<Long, List<String>>>() {
        });



        //遍历搜索规格参数的结果，用来封装map结果
        //处理规格参数显示问题，默认显示id:值，处理后显示id对应的名称:值
        Map<String, Object> specs = new HashMap<>();

        for (SpecParam param : searchParams) {
            //规格参数的id
            Long paramId = param.getId();
            //规格参数的名字
            String name = param.getName();
            //通用参数
            Object value = null;
            if (param.getGeneric()){
                //通用参数
                value = genericMap.get(paramId);

                //判断是否为数值类型，如果是数值类型要考虑分段和单位问题
                if (param.getNumeric()){
                    //数值类型需要加分段
                    value = this.chooseSegment(value.toString(),param);
                }
            }
            else {//特有参数
                value = specialMap.get(paramId);

            }
            if (null==value){
                value="其他";
            }
            specs.put(name,value);
        }

        goods.setSpecs(specs);


        return goods;
    }


    private String chooseSegment(String value, SpecParam p) {
        double val = NumberUtils.toDouble(value);
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = NumberUtils.toDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if(segs.length == 2){
                end = NumberUtils.toDouble(segs[1]);
            }
            // 判断是否在范围内
            if(val >= begin && val < end){
                if(segs.length == 1){
                    result = segs[0] + p.getUnit() + "以上";
                }else if(begin == 0){
                    result = segs[1] + p.getUnit() + "以下";
                }else{
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    public void createIndex(Long id) {

        Spu spu = this.goodsClient.querySpuById(id);

        SpuBo spuBo = new SpuBo();

        BeanUtils.copyProperties(spu,spuBo);

        Goods goods = buildGoods(spuBo);

        goodsRepository.save(goods);
    }

    public void deleteIndex(Long id) {
        goodsRepository.deleteById(id);
    }
}
